#include "databasemanager.h"
#include "sqlhelper.h"
#include "logger.h"


static bool createTable(TableIndex index)
{
    return (SqlHelper::getInstance()->createTable(index) == EttaError::OK);
}

static bool createRole(const Role &role)
{
    return (SqlHelper::getInstance()->insertRole(role) == EttaError::OK);
}

static bool createUser(const User &user)
{
    return (SqlHelper::getInstance()->insertUser(user) == EttaError::OK);
}

static bool setVersion(int major, int minor, int build)
{
    bool ret;
    int curMajor, curMinor, curBuild;
    SqlHelper *sqlHelper = SqlHelper::getInstance();
    ret = sqlHelper->version(curMajor, curMinor, curBuild);
    if (ret)
    {
        if ((curMajor != major) || (curMinor = minor) || (curBuild != build))
        {
            sysDebug("current database version: %d.%d.%d", curMajor, curMinor, curBuild);
            ret = sqlHelper->setVersion(major, minor, build);
            if (ret)
            {
                sysDebug("set database version: %d.%d.%d", major, minor, build);
            }
        }
    }

    return ret;
}

bool DatabaseManager::create(const QString &path)
{
    bool ret = SqlHelper::getInstance()->openDataBase(path);
    if (ret)
    {
        // 创建数据库
        ret = ret && createTable(T_USER);
        ret = ret && createTable(T_ROLE);
        ret = ret && createTable(T_PARAMETER);
        ret = ret && createTable(T_EXPERIMENT);
        ret = ret && createTable(T_MATERIAL);
        ret = ret && createTable(T_LOG);
        ret = ret && createTable(T_FLOW_TEST);
        ret = ret && createTable(T_VOLT_TEST);
        ret = ret && createTable(T_MATERIAL_CODE);
        ret = ret && createTable(T_VERSION);

        // 创建角色
        ret = ret && createRole(Role{"service", 65471, "2022-05-20 18:00:00"});
        ret = ret && createRole(Role{"admin", 49119, "2022-05-20 18:00:00"});
        ret = ret && createRole(Role{"user", 4163, "2022-05-20 18:00:00"});

        // 创建用户
        ret = ret && createUser(User{"service", "Etta2014", "service", "2022-05-20 18:00:00", "Manufacturer", 65471, 1, 0});
        ret = ret && createUser(User{"admin", "Eb1234", "admin", "2022-05-20 18:00:00", "Administrator", 49119, 1, 0});

        // 添加版本号
        ret = ret && setVersion(0, 0, 1);
    }

    return ret;
}

bool DatabaseManager::upgrade()
{
    return true;
}
